package com.yoomiito.app.ui.yijiayou

import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.google.android.material.tabs.TabLayout
import android.view.ViewGroup
import android.widget.FrameLayout
import cn.droidlover.xdroidmvp.net.ApiException
import cn.droidlover.xdroidmvp.net.ApiSubscriber
import cn.droidlover.xdroidmvp.net.XApi
import com.yoomiito.app.BuildConfig
import com.yoomiito.app.R
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.base.WebViewActivity
import com.yoomiito.app.model.LatLng
import com.yoomiito.app.model.OilType4Data
import com.yoomiito.app.model.oil.OilNum
import com.yoomiito.app.model.oil.OilStationDetailData
import com.yoomiito.app.model.oil.OilStationInfo
import com.yoomiito.app.net.YmApi
import com.yoomiito.app.showToast
import com.yoomiito.app.ui.anyview.gasstation.GasStationFormatView
import com.yoomiito.app.utils.ColorUtils
import com.yoomiito.app.utils.Const
import com.yoomiito.app.utils.L
import com.yoomiito.app.utils.UserInfoConfig
import kotlinx.android.synthetic.main.act_oil_station_detail.*
import kotlinx.android.synthetic.main.title_bar.*

class GasStationDetailActivity :BaseActivity<TuanYouDetailPresenter>(){

    private lateinit var formatView: GasStationFormatView
    private lateinit var detailData :OilStationDetailData
    companion object{
        fun start(context: Context,data: OilStationDetailData){
            val intent = Intent(context,GasStationDetailActivity::class.java)
            intent.putExtra(Const.Common.Data, data)
            context.startActivity(intent)
        }
    }

    private lateinit var info: OilStationInfo
    private var mSelectOilNum:OilNum?=null
    private var mSelectOilGunNum = -1

    override fun getLayoutId(): Int  = R.layout.act_oil_station_detail

    override fun newP(): TuanYouDetailPresenter = TuanYouDetailPresenter(App.mAppConfig)

    override fun initData(savedInstanceState: Bundle?) {
        detailData = intent.getSerializableExtra(Const.Common.Data) as OilStationDetailData
        iv_back_left.setOnClickListener{finish()}
        tv_center.text = "加油站详情"
        sure.background = ColorUtils.background(R.color.color_5CB331,23f)
        sure.setOnClickListener {
            //：https://test-open.czb365.com/redirection/todo/?platformType=渠道编码（团油给出）
            //&platformCode=用户唯一标识&gasId=油站 ID&gunNo=油枪号
            if (mSelectOilNum==null||mSelectOilGunNum==-1){
                "请选择枪号".showToast()
            }else{
                if (info.type==4){
                    showLoading()
                  getType4Token()
                }else{
//                    val url = "${BuildConfig.tyu}?platformType=98642997&platformCode=${UserInfoConfig.getUser().mobile}&gasId=${info.id}&gunNo=$mSelectOilGunNum"
//                    WebViewActivity.start(this,url,Const.Url.YiJiaYou)
//                    showLoading()
                    getTuanYouUrl(info.id,mSelectOilGunNum)
                }
            }
        }
        initTabLayout()
        intiFormat()
        info = p.dataHandle(detailData)
        setData()
    }

    private fun intiFormat() {
        formatView = GasStationFormatView(this)
        formatView.onSelectListener = {oilNum, i ->
            mSelectOilGunNum = i
            mSelectOilNum = oilNum
            if (oilNum!=null){
                gasCard.updateInfo(oilNum)
            }

        }
        frameLayout.addView(formatView,FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT))
    }

    private fun initTabLayout() {
        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener{
            override fun onTabReselected(p0: TabLayout.Tab?) {
            }

            override fun onTabUnselected(p0: TabLayout.Tab?) {
            }

            override fun onTabSelected(p0: TabLayout.Tab?) {
                mSelectOilGunNum = -1
                mSelectOilNum = null
                val p = p0?.tag as Int
                val oilNums = info.oilTypes[p].oilNum
                //切换tab 油号保留原有状态(没有选中的油号，则默认第一个) 枪号复原为未选中状态
                oilNums.forEach {
                    if (it.select){
                        gasCard.updateInfo(it)
                        it.oilGunNum.forEach {gunNum->
                            gunNum.select = false
                        }
                    }
                }
                formatView.setOilNum(oilNums)
            }
        })
    }

    private fun setData(){
        gasCard.initInfo(info)
        info.oilTypes.forEachIndexed{index,it->
            if (it.oilNum.size>0){
                val tab = tabLayout.newTab().setText(it.name).setTag(index)
                tabLayout.addTab(tab)
                if (it.select){
                    tab.select()
                    it.oilNum.forEach{oilNum->
                        if (oilNum.select){
                            gasCard.updateInfo(oilNum)//根据油号显示相应的钱
                        }
                    }
                    formatView.setOilNum(info.oilTypes[index].oilNum)//
                }
            }
        }
    }

    private fun getType4Token(){
        YmApi.getYmService()
                .oilType4Token
                .compose(bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(object :ApiSubscriber<OilType4Data>(){

                    override fun onSuccess(t: OilType4Data?) {
                        if (t!=null){
                            val url = "${t.url}placeAnOrder?id=${info.id}&app_name=${t.appName}&token=${t.token}&product_id=${mSelectOilNum?.productId}&gun_id=${mSelectOilGunNum}"
                            WebViewActivity.start(this@GasStationDetailActivity,url)
                        }else{
                            "请重试".showToast()
                        }

                        dismissLoading()
                    }

                    override fun onFail(error: ApiException?) {
                        dismissLoading()
                        "请重试".showToast()
                    }

                })
    }


    private fun getTuanYouUrl(gasId:String,gunNo:Int){
        YmApi.getYmService()
                .getOilCardH5Url(gasId,gunNo)
                .compose(bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(object :ApiSubscriber<OilType4Data>(){

                    override fun onSuccess(t: OilType4Data?) {
                        if (t!=null){
                            WebViewActivity.start(this@GasStationDetailActivity,t.url)
                        }else{
                            "请重试".showToast()
                        }
                        dismissLoading()
                    }

                    override fun onFail(error: ApiException?) {
                        dismissLoading()
                        "请重试".showToast()
                    }

                })
    }
}